﻿using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Threading;

namespace CoupleFil
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void Main()
        {
 
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //OpenWindow(typeof(SpecificationWindow).ToString());
            //SpecificationWindow specification = new SpecificationWindow();
            //specification.MdiParent = this;
            //specification.Show();
            //this.ActivateMdiChild(specification);
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (fp.Q == null)
            {
                MessageBox.Show("Please new or open a project first!");
            }
            else 
                OpenWindow(typeof(SpecificationWindow).ToString());
            

            //if (this.ActiveMdiChild is SpecificationWindow)
            //    this.ActiveMdiChild.Visible = false;
            //else
            //{
            //    foreach (Form childForm in this.MdiChildren)
            //    {
            //        if (childForm is SpecificationWindow)
            //        {
            //            childForm.Visible = true;
            //            this.ActivateMdiChild(childForm);
            //            this.ActiveMdiChild.Activate();
            //            break;
            //        }
            //    }
            //    if (!(this.ActiveMdiChild is SpecificationWindow))
            //    {
            //        SpecificationWindow specification = new SpecificationWindow();
            //        specification.MdiParent = this;
            //        specification.Show();
            //        this.ActivateMdiChild(specification);
            //    }
            //}
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            if (fp.Q == null)
            {
                MessageBox.Show("Please new or open a project first!");
            }
            else
            {
                OpenWindow(typeof(GraphWindow).ToString());
            }
        }        

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            if (fp.Q == null)
            {
                MessageBox.Show("Please new or open a project first!");
            }
            else
                OpenWindow(typeof(MatrixWindow).ToString());            
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            if (fp.Q == null)
            {
                MessageBox.Show("Please new or open a project first!");
            }
            else
                OpenWindow(typeof(StructureWindow).ToString());            
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            if (fp.Q == null)
            {
                MessageBox.Show("Please new or open a project first!");
            }
            else
                OpenWindow(typeof(TopologyMatrix).ToString()); 
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            if (fp.Q == null)
            {
                MessageBox.Show("Please new or open a project first!");
            }
            else
                OpenWindow(typeof(FilterInformation).ToString()); 
        }

        private void speciToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton4_Click(sender, e);
        }

        private void graToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton5_Click(sender,e);
        }

        private void matrixToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton6_Click(sender, e);
        }

        private void structureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton7_Click(sender, e);
        }

        private void approxiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton8_Click(sender, e);
        }

        private void filterInformationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton9_Click(sender, e);
        }

        private void showAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in this.MdiChildren)
                childForm.Visible = true;
        }

        private void closeAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in this.MdiChildren)
                childForm.Close();
        }

        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.Cascade);
        }

        private void toolStripButton11_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void toolStripButton12_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileVertical);
        }

        private void cascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton10_Click(sender, e);
        }

        private void titleHToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton11_Click(sender, e);
        }

        private void titleVToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton12_Click(sender, e);
        }


        private void OpenWindow(string ChildTypeString)
        {

            Form myChild = null;

            if (!ContainMDIChild(ChildTypeString))
            {
                // Get current process assembly
                Assembly assembly = Assembly.GetExecutingAssembly();
                // Create data type using type string
                Type typForm = assembly.GetType(ChildTypeString);
                // Create object using type's "InvokeMember" method
                Object obj = typForm.InvokeMember(
                    null,
                    BindingFlags.DeclaredOnly |
                    BindingFlags.Public | BindingFlags.NonPublic |
                    BindingFlags.Instance | BindingFlags.CreateInstance,
                    null,
                    null,
                    null);
                // Show child form 
                if (obj != null)
                {
                    myChild = obj as Form;
                    myChild.MdiParent = this;
                    myChild.Show();
                    myChild.Focus();
                }
            }
        }

        /// <summary>
        /// Search mdi child form by specific type string
        /// </summary>
        /// <param name="ChildTypeString"></param>
        /// <returns></returns>
        private bool ContainMDIChild(string ChildTypeString)
        {
            Form myMDIChild = null;
            foreach (Form f in this.MdiChildren)
            {
                if (f.GetType().ToString() == ChildTypeString)
                {
                    // found it 
                    myMDIChild = f;
                    break;                    
                }
            }
            // Show the exist form
            if (myMDIChild != null)
            {
                myMDIChild.TopMost = true;
                myMDIChild.Show();
                myMDIChild.Focus();
                return true;
            }
            else
                return false;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (fp.Q != null)
            {
                DialogResult result = MessageBox.Show("Do you want to save current data?", "Save Data", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                    toolStripButton2_Click(sender, e);
            }
            //以SpecificationWindow为主线的版本
            //foreach (Form frm in this.MdiChildren)
            //{
            //    frm.Close();
            //    frm.Dispose();
            //}
            //OpenWindow(typeof(SpecificationWindow).ToString()); 

            //MessageBox.Show(Application.StartupPath);
            OpenFile(Application.StartupPath + "//DefaultCoupleFile.ini");
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (fp.Q == null)
            {
                MessageBox.Show("There is not a project exist yet!");
                return;
            }            
            saveFileDialog1.ShowDialog();            
            if (saveFileDialog1.FileName != "")
            {
                INIClass inifile = new INIClass(saveFileDialog1.FileName); 
                inifile.IniWriteValue("Header", "HighF", fp.HighF.ToString());
                inifile.IniWriteValue("Header", "LowF", fp.LowF.ToString());
                inifile.IniWriteValue("Header", "StartF", fp.StartF.ToString());
                inifile.IniWriteValue("Header", "StopF", fp.StopF.ToString());
                inifile.IniWriteValue("Header", "PoleN", fp.PoleN.ToString());
                inifile.IniWriteValue("Header", "LaVal", fp.LaVal.ToString());
                inifile.IniWriteValue("Header", "RpVal", fp.RpVal.ToString());
                inifile.IniWriteValue("Header", "TzN", fp.TzN.ToString());
                for (int i = 0; i < fp.PoleN ; i++)
                {
                    inifile.IniWriteValue("Q", "Q[" + i + "]", fp.Q[i].ToString());
                }
                for (int i = 0; i < fp.PoleN ; i++)
                {
                    inifile.IniWriteValue("Tz", "Tz[" + i + "]", fp.Tz[i].ToString());
                }
                for (int i = 0; i < fp.PoleN + 2; i++)
                {
                    for (int j = 0; j < fp.PoleN + 2; j++)
                    {
                        inifile.IniWriteValue("cpMatrix", "cpMatrix[" + i + "," + j + "]", fp.cpMatrix[i, j].ToString());
                    }
                }
                for (int i = 0; i < fp.PoleN; i++)
                {
                    for (int j = 0; j < fp.PoleN; j++)
                    {
                        inifile.IniWriteValue("topologyMatrix", "topologyMatrix[" + i + "," + j + "]", fp.topologyMatrix[i, j].ToString());
                    }
                }
            }
        }

        private void SystemIOwrite()         //用System.IO写TXT文件的版本
        {
            if (fp.Q == null)
            {
                MessageBox.Show("There is not a project exist yet!");
                return;
            }
            saveFileDialog1.ShowDialog();
            if (saveFileDialog1.FileName != "")
            {
                using (StreamWriter sw = File.CreateText(saveFileDialog1.FileName))
                {
                    sw.WriteLine("This is a file for filter data");
                    sw.WriteLine("{0}", fp.HighF);
                    sw.WriteLine("{0}", fp.LowF);
                    sw.WriteLine("{0}", fp.StartF);
                    sw.WriteLine("{0}", fp.StopF);
                    sw.WriteLine("{0}", fp.PoleN);
                    sw.WriteLine("{0}", fp.LaVal);
                    sw.WriteLine("{0}", fp.RpVal);
                    sw.WriteLine("{0}", fp.TzN);
                    for (int i = 0; i < fp.PoleN - 1; i++)
                    {
                        sw.Write("{0},", fp.Q[i]);
                    }
                    sw.Write("{0}", fp.Q[fp.PoleN - 1]);
                    sw.WriteLine();
                    for (int i = 0; i < fp.PoleN - 1; i++)
                    {
                        sw.Write("{0},", fp.Tz[i]);
                    }
                    sw.Write("{0}", fp.Tz[fp.PoleN - 1]);
                    sw.WriteLine();
                    for (int i = 0; i < fp.PoleN + 2; i++)
                    {
                        for (int j = 0; j < fp.PoleN + 2; j++)
                            if (i == fp.PoleN + 1 && j == fp.PoleN + 1)
                            {
                                sw.Write("{0}", fp.CpMatrix[i, j]);
                            }
                            else
                            {
                                sw.Write("{0},", fp.CpMatrix[i, j]);
                            }
                    }
                    sw.Close();
                }

            }
        }

        private void OpenFile(string filename)
        {
            //try
            //{
                INIClass inifile = new INIClass(filename);
                if (inifile.ExistINIFile())
                {
                    fp.HighF = double.Parse(inifile.IniReadValue("Header", "HighF", "1"));
                    fp.LowF = double.Parse(inifile.IniReadValue("Header", "LowF", "0.9"));
                    fp.StartF = double.Parse(inifile.IniReadValue("Header", "StartF", "0.94"));
                    fp.StopF = double.Parse(inifile.IniReadValue("Header", "StopF", "0.96"));
                    fp.PoleN = int.Parse(inifile.IniReadValue("Header", "PoleN", "7"));
                    fp.LaVal = double.Parse(inifile.IniReadValue("Header", "LaVal", "26.3828421535949"));
                    fp.RpVal = double.Parse(inifile.IniReadValue("Header", "RpVal", "0.01"));
                    fp.TzN = int.Parse(inifile.IniReadValue("Header", "TzN", "0"));
                    fp.Q = new double[fp.PoleN];
                    for (int i = 0; i < fp.PoleN; i++)
                    {
                        fp.Q[i] = double.Parse(inifile.IniReadValue("Q", "Q[" + i + "]", "5000"));
                    }
                    fp.Tz = new double[fp.PoleN];
                    for (int i = 0; i < fp.PoleN; i++)
                    {
                        fp.Tz[i] = (inifile.IniReadValue("Tz", "Tz[" + i + "]", "正无穷大") == "正无穷大") ? double.PositiveInfinity : double.Parse(inifile.IniReadValue("Tz", "Tz[" + i + "]", "正无穷大"));
                    }
                    fp.CpMatrix = new double[fp.PoleN + 2, fp.PoleN + 2];
                    for (int i = 0; i < fp.PoleN + 2; i++)
                        for (int j = 0; j < fp.PoleN + 2; j++)
                        {
                            //MessageBox.Show(inifile.IniReadValue("cpMatrix", "cpMatrix[" + i + "," + j + "]", "0"));
                            fp.cpMatrix[i, j] = double.Parse(inifile.IniReadValue("cpMatrix", "cpMatrix[" + i + "," + j + "]", "0"));
                        }
                    fp.topologyMatrix = new bool[fp.PoleN, fp.PoleN];
                    for (int i = 0; i < fp.PoleN; i++)
                        for (int j = 0; j < fp.PoleN; j++)
                        {
                            //MessageBox.Show(inifile.IniReadValue("cpMatrix", "cpMatrix[" + i + "," + j + "]", "0"));
                            fp.topologyMatrix[i, j] = bool.Parse(inifile.IniReadValue("topologyMatrix", "topologyMatrix[" + i + "," + j + "]", "0"));
                        }
                    foreach (Form frm in this.MdiChildren)
                    {
                        frm.Close();
                        frm.Dispose();
                    }
                    OpenWindow(typeof(SpecificationWindow).ToString());
                }
                else
                {
                    MessageBox.Show("文件不存在!");
                }
            //}
            //catch (Exception e)
            //{
            //    MessageBox.Show("The file could not be read:" + e.Message);
            //}
        }

        private void SystemIOread(string filename)//用System.IO读TXT文件的版本
        {
            try
            {
                using (StreamReader sr = File.OpenText(filename))
                {
                    String input;
                    input = sr.ReadLine();
                    if (input != "This is a file for filter data")
                    {
                        MessageBox.Show("这不是一个有效的文件或文件已经损坏！");
                        return;
                    }
                    else
                    {
                        input = sr.ReadLine();
                        fp.HighF = double.Parse(input);
                        input = sr.ReadLine();
                        fp.LowF = double.Parse(input);
                        input = sr.ReadLine();
                        fp.StartF = double.Parse(input);
                        input = sr.ReadLine();
                        fp.StopF = double.Parse(input);
                        input = sr.ReadLine();
                        fp.PoleN = int.Parse(input);
                        input = sr.ReadLine();
                        fp.LaVal = double.Parse(input);
                        input = sr.ReadLine();
                        fp.RpVal = double.Parse(input);
                        input = sr.ReadLine();
                        fp.TzN = int.Parse(input);

                        input = sr.ReadLine();
                        string[] Qstr = input.Split(new Char[] { ',' }, fp.PoleN);
                        fp.Q = new double[fp.PoleN];
                        for (int i = 0; i < fp.PoleN; i++)
                        {
                            fp.Q[i] = Convert.ToDouble(Qstr[i]);
                        }
                        input = sr.ReadLine();
                        string[] Tzstr = input.Split(new Char[] { ',' }, fp.PoleN);
                        fp.Tz = new double[fp.PoleN];
                        for (int i = 0; i < fp.PoleN; i++)
                        {
                            //MessageBox.Show(Tzstr[i]);
                            if (Tzstr[i] == "正无穷大")
                            {
                                fp.Tz[i] = double.PositiveInfinity;
                            }
                            else
                            {
                                fp.Tz[i] = Convert.ToDouble(Tzstr[i]);
                            }
                        }
                        input = sr.ReadLine();
                        string[] Cpstr1 = input.Split(new Char[] { ',' }, (fp.PoleN + 2) * (fp.PoleN + 2));
                        fp.cpMatrix = new double[fp.PoleN + 2, fp.PoleN + 2];
                        int n = 0;
                        for (int i = 0; i < fp.PoleN + 2; i++)
                            for (int j = 0; j < fp.PoleN + 2; j++)
                            {
                                fp.cpMatrix[i, j] = double.Parse(Cpstr1[n]);
                                n += 1;
                                //MessageBox.Show(fp1.cpMatrix[i, j].ToString("0.000"));
                            }

                        sr.Close();
                        foreach (Form frm in this.MdiChildren)
                        {
                            frm.Close();
                            frm.Dispose();
                        }
                        OpenWindow(typeof(SpecificationWindow).ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("The file could not be read:" + ex.Message);
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (fp.Q != null)
            {
                DialogResult result = MessageBox.Show("Do you want to save current data?", "Save Data", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                    toolStripButton2_Click(sender, e);
            }
            openFileDialog1.ShowDialog();
            if (openFileDialog1.FileName != "")
            {
                OpenFile(openFileDialog1.FileName);
            }
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton1_Click(sender, e);
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton3_Click(sender, e);
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton2_Click(sender, e);
        }

        private void toolStripButton13_Click(object sender, EventArgs e)
        {
            if (fp.Q == null)
            {
                MessageBox.Show("Please new or open a project first!");
            }
            else
                OpenWindow(typeof(PrintWindow).ToString());  
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            toolStripButton13_Click(sender, e);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About about = new About();
            about.ShowDialog();
        }

        private void toolStripButton14_Click(object sender, EventArgs e)
        {
            try
            {
                if (fp.Q == null)
                {
                    MessageBox.Show("There is not a project exist yet!");
                    return;
                }
                saveFileDialog2.ShowDialog();
                if (saveFileDialog2.FileName != "")
                {
                    string path = saveFileDialog2.FileName;
                    Program.Writes2p(path);                        
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("出现错误：" + ex + ",请与相关人员联系！");
            }
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            toolStripButton14_Click(sender, e);
        }
    }
}